<?php


namespace App\Http\Admin\Controllers;

use Illuminate\Http\Request;
use App\Http\Admin\Controllers\Controller as Controller;
use App\Permission;
use App\Http\Authentication\UserAuthentication;

class PermissionsController  extends Controller{

    use UserAuthentication;

    /*
     * 添加权限
     *
     * @return json
     * */

    public function add_permission(Request $request){



        $data=$request->only("name","display_name","description");

        if(!preg_match('/^[a-zA-Z\-0-9\_]{1,30}$/',$data['name']))  return ThrowApiExc('31001');
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,20}$/u',$data['display_name'])) return ThrowApiExc('31002');
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,40}$/u',$data['description'])) return ThrowApiExc('31002');

        $manageUsers = new Permission;

        $manageUsers->name = $data['name'];//权限名称 只限英文
        $manageUsers->display_name = $data['display_name'];//权限备注
        $manageUsers->description = $data['description'];//权限备注
        $res = $manageUsers->save();

        return [
            'status_code'      => 200,
            'message'     =>  '提交成功',
            'data' => $res
        ];


    }


    /*
     * 查看权限
     * */

    public function select_permission(){



        $manageUers = new Permission;
        $res = $manageUers->get();
        return [
            'status_code'      => 200,
            'message'     =>  '提交成功',
            'data' => $res
        ];
    }

    /*
     * 修改权限
     * */
   //


    public function update_permission(Request $request,$permissionId){


        $data=$request->only("name","display_name",'description');

        if(!preg_match('/^[a-zA-Z\-0-9]{1,30}$/',$data['name']))  return ThrowApiExc('31001');
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,20}$/u',$data['display_name'])) return ThrowApiExc('31002');
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,30}$/u',$data['description'])) return ThrowApiExc('31002');

        $manageUsers = new Permission;

//        $manageUsers->where("id",$permissionId)->update([
//            'name'=>$data['permission'],
//            'display_name'=>$data['permission_description']
//        ]);
        $res = $manageUsers->where("id",$permissionId)->first();
        $res -> name=$data['name'];
        $res -> display_name=$data['display_name'];
        $res -> description=$data['description'];
        $res->save();
        return [
            'status_code'      => 200,
            'message'     =>  '提交成功',
            'data' => []
        ];


    }


    /*
     * 删除权限
     * */

    public function delete_permission($permissionId){


        $manageUsers = new Permission;
        $manageUsers->where("id",$permissionId)->delete();

        return [
            'status_code'      => 200,
            'message'     =>  '删除成功',
            'data' => []
        ];

    }

}
